package com.vshop.timingtask;


import com.vshop.entity.agatewaytobeijing.JsonConstant;
import com.vshop.entity.agatewaytobeijing.Page;
import com.vshop.entity.agatewaytobeijing.syncpackage.response.OriginalPackage;
import com.vshop.entity.agatewaytobeijing.syncpackage.response.ResponseSynchronizePackage;
import com.vshop.entity.agatewaytobeijing.syncpackage.response.SynchronizePackageData;
import com.vshop.entity.comentity.PartnerInfo;
import com.vshop.service.agatewaytobeijing.GatewayToBeijingService;
import com.vshop.service.task.ServicePlanTaskServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


/**
 * 北京给深圳内部使用的同步套餐的接口:2.0接口
 *
 * @author lm
 * @date 2019/5/24
 */

@Configuration
@EnableScheduling
@RestController
@Slf4j
public class SyncPackageNewTask {
    @Value("${system.autoTask}")
    private boolean autoTask;
    @Autowired
    ServicePlanTaskServiceImpl taskService;
    @Autowired
    GatewayToBeijingService toBeijingService;

    @Scheduled(cron = " 0 2 20 * * ?")
    @Async
    @GetMapping(value = "package")
    public void execute() {
        if (autoTask) {
            syncPackageTask();
        }
    }

    public void syncPackageTask() {
        log.info("每1天晚上20点执行一次的syncPackage开始执行");
        //1，取数据库取需要去同步套餐的partnerCode出来,方便可以使用某个固定的企业查询，这边加个参数,""就是取所有
        List<PartnerInfo> partnerList = taskService.findPartnerCode("");

        for (PartnerInfo partner : partnerList) {

            if (StringUtils.isBlank(partner.getPartnerCode()) || StringUtils.isBlank(partner.getSecret()) || StringUtils.isBlank(partner.getPartnerName())) {
                continue;
            }

            //现在去数据库比对当前partnerCode是否是需要去同步套餐和设备的,如果在列表中有记录可以理解返回
            if (taskService.queryOrNotPartnerCode(partner.getPartnerCode()) >= 1) {
                log.info(partner.getPartnerCode() + "：无需请求列表企业");
                continue;
            }

            //把有用的参数拿出来
            String partnerCode = partner.getPartnerCode();
            String partnerName = partner.getPartnerName();
            String secret = partner.getSecret();

            //第一次去请求确定有多少个套餐确定循环需要做多少次
            ResponseSynchronizePackage firstRequest = toBeijingService.synchronizePackage(1, 1, partnerCode, secret);

            //先验证请求结果的response：如果返回的是""就可以直接返回了
            if (StringUtils.isBlank(checkResponseSynchronizePackage(firstRequest))) {
                continue;
            }

            //直接取page的值，拿到一共有多少条数据 去计算需要去执行几次请求
            double total = taskService.countExecutionTimes(firstRequest.getData().getPage());

            //用一个允许控制执行请求的次数
            for (int x = 1; x <= total; x++) {

                log.info("企业是：" + partnerCode + ";一共：" + firstRequest.getData().getPage().getTotal_count() + "条套餐;需执行：" + total + "次;当前是：第" + x + "次");

                //第二次去请求要获得真正的套餐信息
                ResponseSynchronizePackage secondRequest = toBeijingService.synchronizePackage(x, 1000, partnerCode, secret);

                //先验证请求结果的response：如果返回的是""就可以直接返回了
                if (StringUtils.isBlank(checkResponseSynchronizePackage(secondRequest))) {
                    break;
                }

                //开始遍历套餐
                for (OriginalPackage originalPackage : secondRequest.getData().getPackages()) {

                    //先要确保套餐名称和编码是没有问题的
                    if (StringUtils.isBlank(originalPackage.getPackage_code()) || StringUtils.isBlank(originalPackage.getPackage_name())) {
                        continue;
                    }

                    String packageCode = originalPackage.getPackage_code();
                    //先去数据库看看有没有对应这个套餐已经在数据库
                    Integer count = taskService.findPackageByCondition(partnerCode, packageCode);

                    if (count <= 0) {
                        //数据库没有这条记录：入库
                        String continentName = matchData(originalPackage.getCover_country_mcc(), originalPackage.getCover_countrys(), "continentName");
                        String continentNameEN = matchData(originalPackage.getCover_country_mcc(), originalPackage.getCover_countrys(), "continentNameEN");
                        String coverCountryEN = matchData(originalPackage.getCover_country_mcc(), originalPackage.getCover_countrys(), "coverCountryEN");
                        //入库套餐列表
                        taskService.storagePartnerPackage(partnerCode, partnerName, originalPackage, continentName, continentNameEN, coverCountryEN);
                    } else {
                        /*更新数据表里面的serviceCycleCount的值*/
                        taskService.updatePartnerPackageCycleCount(partnerCode, packageCode, originalPackage);
                        //数据库已经有这条数据，我们需要去比对套餐的状态是不是还有效
                        String packageStatus = taskService.queryPackageStatusByCode(partnerCode, packageCode);
                        //获取到的套餐的状态跟数据库的状态不一样，此时要更新数据记录：如果之前是2，现在变成3了的话就要更新
                        boolean b1 = "1".equals(packageStatus) && ("2".equals(originalPackage.getStatus()) || "3".equals(originalPackage.getStatus()));
                        if (b1) {
                            //1，原始套餐：先置于status“已停售-4”;packageStatus置成“停用-3”
                            taskService.updatePackageStatus(partnerCode, packageCode, originalPackage.getStatus(), "4");

                            //2，新建的套餐也要跟着置于废弃状态servicePlanStatus"已停售-4"
                            taskService.updateServicePlanStatus(partnerCode, packageCode, "4");
                        }
                    }

                }
            }
        }
        log.info("每1天晚上20点执行一次的syncPackage执行完毕！");
    }

    /**
     * 验证请求后的响应 ResponseSynchronizePackage
     *
     * @param response
     * @return
     */
    private String checkResponseSynchronizePackage(ResponseSynchronizePackage response) {

        //response响应就是null
        if (null == response) {
            return "";
        }

        //返回的具体的内容是空的或者没有
        if (StringUtils.isBlank(response.getCode()) || StringUtils.isBlank(response.getMessage())) {
            return "";
        }

        //返回的内容不是成功
        boolean b1 = (!JsonConstant.RET_CODE_0000.equals(response.getCode()) && !JsonConstant.RET_CODE_SUCCESS.equals(response.getMessage())) || null == response.getData();
        if (b1) {
            log.info("【同步套餐】响应：" + response.getCode() + ";提示：" + response.getMessage());
            return "";
        }

        SynchronizePackageData data = response.getData();
        if (null == data.getPage() || null == data.getPackage_num() || null == data.getPackages() || data.getPackages().isEmpty()) {
            return "";
        }

        Page page = data.getPage();
        if (StringUtils.isBlank(page.getTotal_count() + "") || page.getTotal_count() <= 0) {
            return "";
        }
        //验证没有问题
        return JsonConstant.RET_CODE_SUCCESS;
    }

    /**
     * 匹配continentName，continentNameEN，coverCountryEN三个字段的值
     *
     * @param mcc
     * @param coverCountry
     * @param condition
     * @return
     */
    private String matchData(String mcc, String coverCountry, String condition) {
        String mccS;
        String continentName = "";
        String continentNameEN = "";
        String coverCountryEN = "";
        //将mcc用；截取，然后拿着数据去查询
        String[] strS = mcc.split(";");

        if (JsonConstant.CODE_CONTINENT_NAME.equals(condition)) {

            for (int i = 0; strS.length > i; i++) {
                mccS = strS[i];
                continentName += taskService.queryContinent(mccS) + ";";
            }
            // 最后一个，去掉
            if (!"".equals(continentName) || !"".equals(coverCountry)) {
                continentName = continentName.substring(0, continentName.length() - 1);
            }
            return continentName;
        } else if (JsonConstant.CODE_CONTINENT_NAME_EN.equals(condition)) {

            for (int i = 0; strS.length > i; i++) {
                mccS = strS[i];
                continentNameEN += taskService.queryContinentEN(mccS) + ";";
            }
            // 最后一个，去掉
            if (!"".equals(continentName) || !"".equals(coverCountry)) {
                continentNameEN = continentNameEN.substring(0, continentNameEN.length() - 1);
            }
            return continentNameEN;
        } else if (JsonConstant.CODE_COVER_COUNTRY_EN.equals(condition)) {

            for (int i = 0; strS.length > i; i++) {
                mccS = strS[i];
                coverCountryEN += taskService.queryCountryEN(mccS) + ";";
            }
            // 最后一个，去掉
            if (!"".equals(continentName) || !"".equals(coverCountry)) {
                coverCountryEN = coverCountryEN.substring(0, coverCountryEN.length() - 1);
            }
            return coverCountryEN;
        } else {
            return "";
        }
    }

}
